package com.dw.dwdzcommerce.tools.manager;

import java.util.ArrayList;
import java.util.List;

import com.dw.dwdzcommerce.base.net.BaseNet;
import com.dw.dwdzcommerce.base.net.NameValuePair;
import com.dw.dwdzcommerce.conf.Constants;
import com.dw.dwdzcommerce.entity.User;
import com.litesuits.orm.LiteOrm;
import com.litesuits.orm.db.DataBase;

import android.content.Context;

public class UserManager implements IUserManager {
	public static boolean isDataChange = false;
	private static UserManager mUserManager;
	private DataBase mDataBase;
	private static Context mContext;

	private UserManager() {
		mDataBase = LiteOrm.newInstance(mContext, Constants.USER_DB_NAME);
	}

	public static UserManager getManager(Context context) {
		if (mUserManager == null) {
			synchronized (UserManager.class) {
				if (mUserManager == null) {
					synchronized (UserManager.class) {
						mContext = context.getApplicationContext();
						mUserManager = new UserManager();
					}
				}
			}
		}
		return mUserManager;
	}

	/**
	 * 获取本地的user
	 * 
	 * @return
	 */
	public User getLocalUser() {
		ArrayList<User> userLists = mDataBase.queryAll(User.class);
		if (userLists.isEmpty()) {
			return null;
		}
		return userLists.get(0);
	}

	/**
	 * 将user缓存到本地
	 * 
	 * @param user
	 * @return
	 */
	public synchronized boolean cacheLocalUser(User user) {
		if (user == null) {
			return false;
		}
		mDataBase.deleteAll(User.class);
		mDataBase.save(user);
		return true;
	}

	/**
	 * 将user缓存到本地并上传到服务器
	 */
	@Override
	public synchronized boolean uploadUser(BaseNet net, User user) {
		isDataChange=true;
		boolean cacheLocalUser = cacheLocalUser(user);
		sendToService(net);
		return cacheLocalUser;
	}

	/**
	 * 如果数据有变化，则从网络刷新数据，不然就直接获取本地数据
	 * @param net
	 * @param userId 通过userId到服务器拉下用户数据
	 * @return 如果数据已经变化，返回null，并从网络加载，如果数据没有变化，直接返回当前本地的user
	 */
	public synchronized User getUserAnyWhere(BaseNet net, String userId) {
		if(!isDataChange){
			return getLocalUser();
		}
		getFromNet(net,userId);
		isDataChange=false;
		return null;
	}

	private void getFromNet(BaseNet net, String userId) {
		List<NameValuePair> values = new ArrayList<NameValuePair>();
		throw new RuntimeException("现在是单机版，网络不可用");
	}

	/**
	 * 发送到服务器
	 * 
	 * @param net
	 */
	private void sendToService(BaseNet net) {
		List<NameValuePair> values = new ArrayList<NameValuePair>();
		throw new RuntimeException("现在是单机版，网络不可用");
		// net.sendData(Constants.URL_REFRESH_USER, values);
	}

	/**
	 * 退出登录
	 * 
	 * @return
	 */
	public boolean logout() {
		User localUser = getLocalUser();
		if (localUser == null) {
			return false;
		}
		mDataBase.deleteAll(User.class);
		return true;
	}

}
